package com.web.exiaodao.business.service.impl;

import com.web.exiaodao.business.entity.FanliFlow;
import com.web.exiaodao.business.repository.FanliFlowRepository;
import com.web.exiaodao.business.service.FanliFlowService;
import com.web.exiaodao.remote.vo.FanliBusinessVo;
import com.web.exiaodao.remote.vo.FanliFlowVo;
import com.web.exiaodao.remote.vo.UserVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.excelUtil.ExcelColumn;
import com.web.webstart.base.excelUtil.ExcelHead;
import com.web.webstart.base.excelUtil.ExcelHelper;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("FanliFlowService")
@Transactional(readOnly = false)
public class FanliFlowServiceImpl extends BaseService<FanliFlow> implements FanliFlowService {

	private static final Logger LOGGER = Logger.getLogger(FanliFlowServiceImpl.class);

	@Autowired
	private FanliFlowRepository fanliFlowRepository;
	
	/**
	 * 查询单条FanliFlow信息
	 * //@param tId
	 * @return 返回单个FanliFlow对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<FanliFlow> findOne(Long modelId) throws BusinessException {
		FanliFlow obj = new FanliFlow();
		if(modelId != 0){
			obj = fanliFlowRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<FanliFlow> xr = new XaResult<FanliFlow>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(obj);
			LOGGER.info("后台----->查询单个实体----->FanliFlow");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的FanliFlow数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象FanliFlow集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<FanliFlow>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<FanliFlow> page = fanliFlowRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), FanliFlow.class), pageable);
		XaResult<Page<FanliFlow>> xr = new XaResult<Page<FanliFlow>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态不等于）----->FanliFlow");
		return xr;
	}

	/**
	 * 分页查询状态status的FanliFlow数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象FanliFlow集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<FanliFlow>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<FanliFlow> page = fanliFlowRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), FanliFlow.class), pageable);
		XaResult<Page<FanliFlow>> xr = new XaResult<Page<FanliFlow>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态等于）----->FanliFlow");
		return xr;
	}

	/**
	 * 保存FanliFlow信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<FanliFlow> saveOrUpdate(FanliFlow model) throws BusinessException {
		FanliFlow obj = null;
		if(XaUtil.isNotEmpty(model.getId())){
			obj = fanliFlowRepository.findOne(model.getId());
		}else{
			obj = new FanliFlow();
		}
	obj.setCreateUser(XaUtil.isNotEmpty(model.getCreateUser()) ? model.getCreateUser() : obj.getCreateUser());
	    obj.setBusId(XaUtil.isNotEmpty(model.getBusId()) ? model.getBusId() : obj.getBusId());
	    obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
	    obj.setExukey(XaUtil.isNotEmpty(model.getExukey()) ? model.getExukey() : obj.getExukey());
		obj = fanliFlowRepository.save(obj);
		XaResult<FanliFlow> xr = new XaResult<FanliFlow>();
		xr.setObject(obj);
		LOGGER.info("后台新增或编辑数据成功！");
		return xr;
	}

	/**
	 * 修改FanliFlow状态，可一次修改多条   3删除  -1锁定  1正常
	 * //@param userId
	 * @param modelIds
	 * @param status
	 * @return 返回FanliFlow对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<FanliFlow> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<FanliFlow> xr = new XaResult<FanliFlow>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				FanliFlow obj = fanliFlowRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = fanliFlowRepository.save(obj);
				}
			}
		}
		LOGGER.info("批量修改数据状态成功！");
		return xr;
	}

	//查询入口流量列表
	@Override
	public XaResult<Page<FanliFlowVo>> findFanliFlowList(Integer status,
			Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		StringBuffer sql = new StringBuffer("SELECT ff.`id`,fb.`business_name`,u.`user_name`,ff.`exukey`,ff.`create_time`,ff.`status` ");
		sql.append("FROM `tb_xa_fanliflow` ff  ");
		sql.append("LEFT JOIN `tb_xa_fanlibusiness` fb ON fb.`id` = ff.bus_id ");
		sql.append("LEFT JOIN `tb_xa_user` u ON u.`id` = ff.`user_id` ");
		sql.append("WHERE ff.`status`<>").append(XaConstant.Status.delete).append(" AND fb.`status`<>").append(XaConstant.Status.delete);
		sql.append(" AND u.status<>").append(XaConstant.Status.delete);
		//查询条件
		if(XaUtil.isNotEmpty(filterParams.get("LIKE_businessName"))){
			sql.append(" AND fb.business_name ").append(" like '%").append(filterParams.get("LIKE_businessName")).append("%' ");
		}
		if(XaUtil.isNotEmpty(filterParams.get("LIKE_userName"))){
			sql.append(" AND u.user_name ").append(" like '%").append(filterParams.get("LIKE_userName")).append("%' ");
		}
		sql.append(" ORDER BY ff.`create_time` DESC");
		List<Object[]> objs = this.query(sql.toString(), pageable.getPageNumber()*pageable.getPageSize(), pageable.getPageSize());
		List<FanliFlowVo> vos = new ArrayList<FanliFlowVo>();
		for (Object[] obj : objs) {
			FanliFlowVo vo = new FanliFlowVo();
			FanliBusinessVo fb = new FanliBusinessVo();
			UserVo uVo = new UserVo();
			vo.setId(Long.valueOf(obj[0].toString()));
			fb.setBusinessName(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
			uVo.setUserName(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
			vo.setExukey(XaUtil.isEmpty(obj[3])?"":obj[3].toString());
			vo.setCreateTime(XaUtil.isEmpty(obj[4])?"":obj[4].toString());
			vo.setStatus(XaUtil.isEmpty(obj[5])?0:Integer.valueOf(obj[5].toString()));
			vo.setUserVo(uVo);
			vo.setFanliBusinessVo(fb);
			vos.add(vo);
		}
		int count=objs.size();	
		Page<FanliFlowVo> page= new MyPage<FanliFlowVo>(pageable.getPageNumber(),pageable.getPageSize(),vos,count);
		XaResult<Page<FanliFlowVo>> xr=new XaResult<Page<FanliFlowVo>>();
		xr.setObject(page);
		return xr;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void exportdata(Map<String, Object> filterParams,
			HttpServletResponse response, String modelIds)
			throws BusinessException {
		Pageable pageable = WebUitl.buildPageRequest(0, Integer.MAX_VALUE, "[{property:'createTime',direction:'DESC'}]");
        Page<FanliFlowVo> page = this.findFanliFlowList(XaConstant.Status.delete, filterParams, pageable).getObject();
        List<FanliFlowVo> ffVoList = new ArrayList<>();
        if (XaUtil.isNotEmpty(page) && XaUtil.isNotEmpty(page.getContent())) {
            ffVoList.addAll(page.getContent());
        }
        
        //excel结构
        List<ExcelColumn> excelColumns = new ArrayList<ExcelColumn>();
        excelColumns.add(new ExcelColumn(0, "id", "编号", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(1, "fanliBusinessVo.businessName", "商家中文名称", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(2, "userVo.userName", "跳转用户", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(3, "exukey", "跳转exukey", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(4, "createTime", "跳转时间", Cell.CELL_TYPE_STRING));
        excelColumns.add(new ExcelColumn(5, "status", "状态", Cell.CELL_TYPE_STRING));

        // 需要特殊转换的单元 map的可以必须好实体的类型一致
        Map<String, Map> excelColumnsConvertMap = new HashMap<>();
        Map<Integer, String> isReceive = new HashMap<>();
        isReceive.put(-1, "锁定");
        isReceive.put(0, "无效");
        isReceive.put(1, "正常");
        isReceive.put(2, "发布/启用/通过");
        isReceive.put(3, "删除");
        isReceive.put(4, "发出");
        excelColumnsConvertMap.put("status", isReceive);

        //设置头部
        ExcelHead head = new ExcelHead();
        head.setRowCount(1); // 模板中头部所占行数
        head.setColumns(excelColumns);  // 列的定义
        head.setColumnsConvertMap(excelColumnsConvertMap); // 列的转换
        //执行导出,第一个null是response参数，用来输出到浏览器，第二个null是要导出的数据集合
        ExcelHelper.getInstanse().exportExcelFile(response, head, ffVoList);
	}
	
}
